package com.oa.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oa.Response.ResponseData;
import com.oa.Response.Result;
import com.oa.config.redis.RedisCache;
import com.oa.entity.domain.User;
import com.oa.entity.dto.UserAndRole;
import com.oa.entity.vo.LoginUser;
import com.oa.entity.vo.UserFormVo;
import com.oa.mapper.UserMapper;
import com.oa.service.UserService;
import com.oa.utils.jwt.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {

    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;

    //登录
    @Override
    public ResponseData<Map<String,String>> login(UserFormVo userFormVo) {
        //Authentication    进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userFormVo.getUsername(),userFormVo.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("登录失败");
        }
        //认证通过,得到userdetail对象
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        //获取LoginUser中的密码，与用户输入密码进项比较
        if(!passwordEncoder.matches(userFormVo.getPassword(),loginUser.getUser().getPassword())){
            return new ResponseData<>(400,"密码错误",null);
        };
        //获取 userid，生成token
        String userid = loginUser.getUser().getId().toString();
         User user1 = loginUser.getUser();
//         String userString=JSON.toJSONString(user1);
        String jwt = JwtUtils. createToken(user1,60*60*1000l);

        //将用户信息存入redis   userid作为key
        redisCache.setCacheObject("login:"+userid, loginUser);

        //jwt存入ResponseResult返回
        Map<String,String>map=new HashMap<>();
        map.put("token",jwt);
       return  new ResponseData<>(200,"登录成功",map);
    }

    //注册
    @Override
    public Result<Map<String, String>> resginter(UserFormVo userFormVo) {
        //获取用户名，密码
        String username=userFormVo.getUsername();
        String password=userFormVo.getPassword();
        //判断用户名是否存在   判断用户是否已经存在
        if(!Objects.isNull(userMapper.findByName(username))
                || !Objects.isNull(userMapper.findByNameAndPassword(username,password))){
            return new Result<>(403,"该用户名存在或用户已存在",null);
        }
        //生成用户
        User user=new User();
        user.setName(username);
        //密码加密
        String newpa=passwordEncoder.encode(password);
        user.setPassword(newpa);
        //添加用户     给用户添加角色,默认系统管理员，执行所有操作
        userMapper.insert(user);
        Integer uid=userMapper.findByName(username).getId();
        userMapper.addRole(uid,1);
        //返回给前端
        return  Result.regSuccess(null);
    }

    //退出登录
    @Override
    public ResponseData logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getUser().getId();
        //删除redis中相应的用户信息
        redisCache.deleteObject("login:"+userid);
        return  new ResponseData(200,"注销成功",null);
    }

     //获取登录用户信息
    public ResponseData<UserAndRole> getUserInfo() {
        //从AuthenticationContextHolder中获取authentication
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //认证当前用户
        //获取当前登录用户
        LoginUser  loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();
        //生成UserAndRole对象
        UserAndRole userAndRole=new UserAndRole();
        userAndRole.setUsername(user.getName());
        userAndRole.setRole("系统管理员");
        userAndRole.setLoginTime(LocalDateTime.now());
        //返回数据
        return  new ResponseData<>(200,"OK",userAndRole);
    }

    //获取所有用户信息
    @Override
    public ResponseData<List<User>> getAllUser() {
        //获取用户列表
        List<User> users = userMapper.selectList(null);
        //将用户信息传给前端
        return new ResponseData<>(200,"OK",users);
    }
    //更新用户
    @Override
    public ResponseData updateUser(Integer id,String name) {
        //如果名字为空，表示没有修改
        if(name==null){
            return new ResponseData(400,"fail",null);
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("name", name);
        userMapper.update(null, updateWrapper);
        return new ResponseData(200,"OK",null);
    }
   //删除用户
    @Override
    public ResponseData deleteUser(Integer id) {
        userMapper.deleteById(id);
        return new ResponseData(200,"删除成功",null);
    }

    @Override
    public ResponseData<List<User>> getUserBySomething(Object msg) {
        List<User> users = userMapper.getUserBySomething(msg);
        return new ResponseData<>(200,"ok",users);
    }

//    public User getByNameAndPassword(String username, String password){
//        return userMapper.findByNameAndPassword(username,password);
//    }
}
